#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>

#define BUFFER_SIZE 4096

// 解析域名，获取 IP 地址
std::string resolve_host(const std::string& host) {
    struct hostent *he = gethostbyname(host.c_str());
    if (he == nullptr) {
        std::cerr << "Error: Could not resolve host " << host << std::endl;
        return "";
    }
    struct in_addr **addr_list = (struct in_addr **)he->h_addr_list;
    return inet_ntoa(*addr_list[0]);
}

// 创建并连接到服务器的 socket
int create_socket(const std::string& host, int port) {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        std::cerr << "Error: Could not create socket" << std::endl;
        return -1;
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(host.c_str());

    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        std::cerr << "Error: Could not connect to server" << std::endl;
        close(sockfd);
        return -1;
    }

    return sockfd;
}

// 发送 HTTP 请求
void send_http_request(int sockfd, const std::string& host, const std::string& path) {
    std::stringstream request;
    request << "GET " << path << " HTTP/1.1\r\n"
            << "Host: " << host << "\r\n"
            << "Connection: close\r\n"
            << "User-Agent: Mozilla/5.0\r\n"
            << "\r\n";

    std::string request_str = request.str();
    send(sockfd, request_str.c_str(), request_str.length(), 0);
}

// 接收响应并保存图片
void receive_and_save_image(int sockfd, const std::string& output_file) {
    char buffer[BUFFER_SIZE];
    std::ofstream out_file(output_file, std::ios::binary);
    if (!out_file) {
        std::cerr << "Error: Could not open file for writing" << std::endl;
        return;
    }

    ssize_t bytes_received;
    while ((bytes_received = recv(sockfd, buffer, sizeof(buffer), 0)) > 0) {
        out_file.write(buffer, bytes_received);
    }

    if (bytes_received == -1) {
        std::cerr << "Error: Failed to receive data" << std::endl;
    }

    out_file.close();
}

int main() {
    std::string url = "http://47.113.221.55/image/1.png"; // URL 请求
    std::string host = "47.113.221.55";                  // 服务器地址
    std::string path = "/image/1.png";                   // 图片路径
    std::string output_file = "downloaded_image.png";    // 保存图片的文件名

    // 创建 socket 并连接到服务器
    int sockfd = create_socket(host, 80);
    if (sockfd == -1) {
        return -1;
    }

    // 发送 HTTP 请求
    send_http_request(sockfd, host, path);

    // 接收图片数据并保存到文件
    receive_and_save_image(sockfd, output_file);

    std::cout << "Image downloaded successfully and saved as " << output_file << std::endl;

    // 关闭 socket
    close(sockfd);
    return 0;
}
